<template>
    <el-select ref="mySelect" v-model="selectTreeLabel" :disabled="disabled" popper-class="select-tree">
        <el-option value=" ">
            <el-tree
                ref="myTree"
                :filter-node-method="filterNode"
                :node-key="nodeKey"
                :data="data"
                :default-expand-all="true"
                :highlight-current="true"
                :current-node-key="value"
                :expand-on-click-node="false"
                :show-checkbox="showCheckbox"
                :props="props"
                :lazy="lazy"
                :load="load"
                @node-click="handleNodeClick">
            </el-tree>
        </el-option>
    </el-select>
</template>
<script>
export default {
    name: 'select-tree',
    // props参照element-ui tree props
    props: {
        data: {
            type: Array
        },
        showCheckbox: {
            'type': Boolean,
            'default': false
        },
        props: {
            default() {
                return {
                    children: 'children',
                    label: 'label',
                    nodeKey: 'id',
                    icon: 'icon'
                };
            }
        },
        lazy: {
            type: Boolean,
            default: false
        },
        load: {
            type: Function
        },
        value: {
            required: true
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    mounted() {
        this.init();
    },
    computed: {
        // 节点标志属性，通常为id
        nodeKey() {
            return this.props.nodeKey || 'id';
        },
        // 节点显示内容属性
        label() {
            return this.props.label || 'label';
        }
    },
    data() {
        return {
            selectTreeLabel: ''
        };
    },
    watch: {
        value(val, oldVal) {
            this.setSelectTreeValue();
        }
    },
    methods: {
        init() {
            this.setSelectTreeValue();
        },
        // 根据用户传参，修改select tree显示
        setSelectTreeValue() {
            setTimeout(() => {
                this.$refs.myTree.filter(this.value);
            }, 0);
        },
        // 配合filter获取选中的label内容
        filterNode(value, data, node) {
            if (data[this.nodeKey] === value) {
                this.selectTreeLabel = data[this.label];
            }
            return true;
        },
        handleNodeClick(data, node, vueComponent) {
            this.$refs.mySelect.visible = false;
            this.$emit('input', data[this.nodeKey]);
        }
    }
};
</script>
<style lang="less">
.select-tree {
    .el-select-dropdown__list {
        border: 0;
        height: auto;
        padding: 0;
    }
    .el-select-dropdown__item {
        height: auto;
        padding: 0;
    }
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
        background-color: #e0e0e0;
    }
}
</style>
